import {
  Component,
  OnInit,
  Injector,
  Input,
  Output,
  EventEmitter,
} from '@angular/core';
import {
  RoleServiceProxy,
  RoleListDto,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';

@Component({
  selector: 'role-combox',
  templateUrl: './role-combox.component.html',
})
export class RoleComboxComponent extends AppComponentBase implements OnInit {
  @Input() placeholder: string;
  @Input() selectedRole: RoleListDto = undefined;
  @Output() selectedRoleChange: EventEmitter<RoleListDto> = new EventEmitter<RoleListDto>();
  roles: RoleListDto[] = [];
  private _roleId: number;

  constructor(private _roleService: RoleServiceProxy, injector: Injector) {
    super(injector);
  }

  ngOnInit(): void {
    this._roleService.getRoles(undefined).subscribe(result => {
      this.roles = result.items;
    });
  }

  autoSelect() {
    if (!this.roles || !this._roleId) {
      return;
    }
    this.selectedRole = this.roles.find(item => item.id == this._roleId);
    if (this.selectedRoleChange) {
      this.selectedRoleChange.emit(this.selectedRole);
    }
  }
}
